﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using QMERP.Infrastructure.EFCore;

namespace QMERP.WebApi.Filter
{
    public class TransactionFilterAttribute : TypeFilterAttribute
    {
        public TransactionFilterAttribute() : base(typeof(TransactionActionFilter))
        {
        }
        public class TransactionActionFilter : IActionFilter
        {
            private IDbContextTransaction? _transaction;
            private QMERPDbContext? _db;
            public void OnActionExecuting(ActionExecutingContext context)
            {
                _db = (QMERPDbContext)context.HttpContext.RequestServices.GetService(typeof(QMERPDbContext))!;
                _transaction = _db?.Database.BeginTransaction();
            }
            public void OnActionExecuted(ActionExecutedContext context)
            {
                if (context.Exception == null)
                {
                    _transaction?.Commit();
                }
                else
                {
                    _transaction?.Rollback();
                    var entries = _db?.ChangeTracker.Entries().Where(x => x.State != EntityState.Detached);
                    if (entries != null)
                    {
                        foreach (var entry in entries)
                        {
                            entry.State = EntityState.Detached;
                        }
                    }
                }
                _transaction?.Dispose();
            }
        }
    }
}
